#!/bin/bash

LOCK=
CMD=
STATUS=
LOG=/dev/null

echo "jobs ${JOB_ID} process $$"

while [ $# -gt 0 ]
do
	if [ "$1" == "-l" ]; then
		shift
		LOCK=$1
	elif [ "$1" == "-c" ]; then
		shift
		CMD=$1
	elif [ "$1" == "-m" ]; then
		shift
		STATUS=$1
	elif [ "$1" == "--log" ]; then
		shift
		LOG=$1
	else
		echo "ERROR: casper-run.sh: unrecognized parameter \"$1\"" >&2
		exit 1
	fi
	shift
done

if [ -z "$CMD" ]; then
	echo "ERROR: casper-run.sh: command not specified" >&2
	exit 1
fi
if [ -z "$LOCK" ]; then
	echo "ERROR: casper-run.sh: lock category not specified" >&2
	exit 1
fi

# Taking lock
NODE=`casper-lock -c $LOCK`
if [ $? -ne 0 ]; then
	echo "ERROR: casper-run.sh: unable to get lock over category $LOCK" >&2
	exit 1
fi
if [ ! -z "${STATUS}" ]; then
	echo "jobs ${JOB_ID} status ${STATUS}"
fi
# Lock granted on node $NODE
if [ `hostname` == "$NODE" ]; then
	# Run locally
	$CMD > ${LOG} &
	echo "jobs ${JOB_ID} process $!"
	wait $!
	EXIT_STATUS=$?
	echo "jobs ${JOB_ID} process-term $!"
else
	# Run on a remote host
	trap "{ rocks run host $NODE \"killall ${CMD}\" ; }" SIGABRT
	rocks run host $NODE "source ${CASPER_WORK_DIR}/${JOB_ID}/variables ; ${CMD} > ${LOG}"
	EXIT_STATUS=$?
	trap "-" SIGABRT
fi

casper-lock -u ${NODE}

if [ ${EXIT_STATUS} -ne 0 ]; then
	echo "ERROR: casper-run.sh: \"$CMD\" terminated with exit code ${EXIT_STATUS}" >&2
fi

exit ${EXIT_STATUS}
